# asciidoctor-pdf basic-example.adoc
# docs
# find . -name "*.pdf" -type f -delete
import datetime
import fnmatch
import os
import shutil
import subprocess
import concurrent.futures


def get_project_and_doc_path(docs_folder: str) -> tuple[str, str]:
    # 获取当前脚本所在的目录
    project_path = os.path.dirname(os.path.realpath(__file__))
    docs_folder_full_path = os.path.join(project_path, docs_folder)
    # 判断文件夹是否存在,不存在则打印错误信息并抛出异常
    if not os.path.exists(docs_folder_full_path):
        print(f"folder: {docs_folder_full_path} does not exist")
        raise FileNotFoundError
    return project_path, docs_folder_full_path


def get_adoc_file_list(docs_folder_full_path: str) -> list[str]:
    # 获取文件夹(递归获取,包括所有的子文件夹)下所有后缀为.adoc的文件的绝对路径,并存储到一个列表中
    adoc_files = find_adoc_files(directory=docs_folder_full_path)
    print(f"adoc_files:{adoc_files}")
    return adoc_files


def find_adoc_files(directory: str) -> list[str]:
    adoc_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if fnmatch.fnmatch(file, '*.adoc'):
                adoc_files.append(os.path.join(root, file))
    return adoc_files


def convert_adoc_to_pdf(adoc_file: str):
    command = f"asciidoctor-pdf \"{adoc_file}\""
    process = subprocess.Popen(command, shell=True)
    process.wait()


def batch_convert(adoc_files: list[str]):
    cpu_count = os.cpu_count()
    with concurrent.futures.ThreadPoolExecutor(max_workers=cpu_count) as executor:
        futures = {executor.submit(convert_adoc_to_pdf, adoc_file) for adoc_file in adoc_files}
        concurrent.futures.wait(futures)


def copy_directory_with_timestamp(src_dir: str) -> str:
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    dst_dir = f"{src_dir}_{timestamp}"
    shutil.copytree(src_dir, dst_dir)
    return dst_dir


def delete_files(folder: str, file_extension: str):
    command = f"find {folder} -name \"*.{file_extension}\" -type f -delete"
    print(f"command: {command}")
    process = subprocess.Popen(command, shell=True)
    process.wait()


def compress_directory_to_zip(directory):
    output_filename = f"{directory}.zip"
    shutil.make_archive(directory, 'zip', directory)
    return os.path.abspath(output_filename)


if __name__ == '__main__':
    docs_folder = "docs"
    project_path, docs_folder_full_path = get_project_and_doc_path(docs_folder)
    print("get adoc file list")

    adoc_files = get_adoc_file_list(docs_folder_full_path=docs_folder_full_path)
    print("start to convert adoc to pdf")
    batch_convert(adoc_files)
    print("end to convert adoc to pdf")

    copy_dir = copy_directory_with_timestamp(src_dir=docs_folder_full_path)
    print(f"delete pdf files in {docs_folder_full_path}")
    delete_files(folder=docs_folder_full_path, file_extension="pdf")
    print(f"delete adoc files in {copy_dir}")
    delete_files(folder=copy_dir, file_extension="adoc")
    zip_file = compress_directory_to_zip(copy_dir)
    print(f"zip file: {zip_file}")
